import { useEffect, useState, useCallback, useRef } from 'react';
import { List, Checkbox, Toast } from 'antd-mobile';
import service from './service';
import SimpleListView from '@inbiz/basic/SimpleListView';
import styles from './index.less';
import Breadcrumb from '../SyncComponents/WapBreadcrumb';
import { getParents } from './utils';
import SelectBar from './SelectBar';
import { getLowercase } from './utils/index';
import _ from 'lodash';
import { getMessage } from '@inbiz/react';

export default function PositionTab(props: any) {
  const listRef = useRef<any>();
  const [data, _data] = useState<any[]>([]);
  const [bread, _bread] = useState<any[]>([]);
  const [breadId, _breadId] = useState<number[]>([]);
  const { selected, selectedId, allSelected, multiple, onCancel, onOk, setSelected, tabKey } =
    props;
  let currentPosId = breadId[breadId.length - 1];

  const setBread = (breads: any[]) => {
    _bread(breads);
    _breadId(breads.map((v) => v.identityid));
  };

  const onRefresh = useCallback(
    (params: any) => {
      let row = breadId.length ? bread[bread.length - 1] : {};
      let _params = breadId.length
        ? {
          positionId: row.identityid,
          id: row.id,
        }
        : { positionIds: [1] };
      service[breadId.length ? 'getSubPositionList' : 'getTopPositionList'](_params).then((res) => {
        if (res.Success) {
          let arrData = Array.isArray(res.OtherData) ? res.OtherData || [] : [res.OtherData];
          _data(arrData);
          // 每次刷新滚动到顶部
          listRef.current?.scroll(0, 0);
        }
      });
    },
    [breadId, currentPosId],
  );

  const onRowSelectChange = useCallback(
    (row: any) => {
      return (checked: boolean) => {
        let index = selectedId.indexOf(row.key);
        if (checked) {
          if (index == -1) {
            let newSelected = [...selected, row];
            setSelected(newSelected);
          }
        } else {
          if (index > -1) {
            let newSelected = [...selected];
            newSelected.splice(index, 1);
            setSelected(newSelected);
          }
        }
        props.updateSelected && props.updateSelected(checked, row);
      };
    },
    [selectedId, selected],
  );

  const onClickRow = useCallback(
    (e: any, row: any, index: number) => {
      let p = getParents(e.target, e.currentTarget.querySelector('.adm-list-item-content-extra'));
      if (p.length) {
        return;
      }
      service
        .getSubPositionList({
          positionId: row.identityid,
          id: row.id,
        })
        .then((res) => {
          if (!_.isEmpty(res)) {
            let newBread = [...bread, row];
            setBread(newBread);
            _data(getLowercase(res, tabKey));
          } else {
            Toast.show({
              // 该职位下没有子职位
              content: getMessage(`WapMemberSelect.lang.noSubPosition`),
            });
          }
        });
    },
    [bread, breadId],
  );

  const onBreadItemClick = useCallback(
    (e, row, index) => {
      if (index == -1) {
        service.getTopPositionList({ positionIds: [1] }).then((res) => {
          if (res) {
            _data(getLowercase(res, tabKey));
            setBread([]);
          }
        });
      } else {
        service
          .getSubPositionList({
            positionId: row.identityid,
            id: row.id,
          })
          .then((res) => {
            if (res) {
              let newBreads = [...bread].slice(0, index + 1);
              setBread(newBreads);
              _data(getLowercase(res, tabKey));
            } else {
              Toast.show({
                // 该职位下没有子职位
                content: getMessage(`WapMemberSelect.lang.noSubPosition`),
              });
            }
          });
      }
    },
    [bread],
  );

  useEffect(() => {
    service.getTopPositionList({ positionIds: [1] }).then((res) => {
      if (res) {
        _data(getLowercase(res, tabKey));
      }
    });
  }, []);

  return (
    <div className={styles.positionTab}>
      {bread.length ? (
        <Breadcrumb
          nameKey={'name'}
          data={bread}
          onBreadItemClick={onBreadItemClick}
          showHome={true}
          onClickHome={() => {
            onBreadItemClick(null, null, -1);
          }}
          itemStyle={{ fontSize: 16 }}
        />
      ) : null}
      <SimpleListView
        style={{
          height: bread.length ? 'calc(100% - 45px)' : '100%',
        }}
        ref={listRef}
        onRefresh={onRefresh}
        renderRow={(row: any, index: number) => {
          return (
            <List.Item
              key={index}
              arrow={false}
              extra={
                <Checkbox
                  checked={selectedId.includes(row.key)}
                  onChange={onRowSelectChange(row)}
                />
              }
              onClick={(e) => onClickRow(e, row, index)}
            >
              {row.name}
            </List.Item>
          );
        }}
        dataSource={data}
      />
      <SelectBar
        filterKey={tabKey}
        data={data}
        selectedId={selectedId}
        selected={selected}
        allSelected={allSelected}
        multiple={multiple}
        setSelected={setSelected}
        onOk={onOk}
        onCancel={onCancel}
      />
    </div>
  );
}
